require 'fileutils'

class Brand < ActiveRecord::Base
  attr_accessible :name, :status, :url, :logo, :meta_keywords, 
    :meta_description, :description, :logo_pic
  
  validates_presence_of :name
  validates_uniqueness_of :name
  
  attr_accessor :logo_pic
  
  before_save :upload_logo
  
  STATUSES = { 0 => '默认', 2 => '首页推荐', -1 => '删除' }
  
  named_scope :valid, :conditions => ['status >= ?', 0]
  
  named_scope :filter, lambda { |params|
    c, h = [], {}
    
    unless params[:id].blank?
      c << "id LIKE :id"
      h[:id] = "%#{params[:id]}%"
    end
    unless params[:name].blank?
      c << "name LIKE :name"
      h[:name] = "%#{params[:name]}%"
    end
    
    { :conditions => [c.join(' AND '), h] }
  }
  
  class << self
    
    def status_options
      STATUSES.inject([]){ |arr, obj| arr << obj.reverse }
    end
    
  end
  
  def to_s
    name
  end
  
  def display_status
    STATUSES[status]
  end
  
  def del
    update_attributes!(:status => -1)
  end

  protected
  
    def upload_logo
      unless self.logo_pic.blank?
        FileUtils.mkdir_p(absolute_path) unless File.exist?(absolute_path)
        FileUtils.remove_file(current_full_path) if !self.new_record? and File.exist?(current_full_path)
        
        File.open(full_path, 'wb') { |f| f.write(self.logo_pic.read) }      
        self.logo = logo_url
      end
    end

    def logo_path
      'brands/logo/'
    end
  
    def absolute_path
      File.join(RAILS_ROOT, 'public', logo_path)
    end

    def logo_filename
      return logo_pic.original_filename if self.new_record?
      self.id.to_s + File.extname(logo_pic.original_filename)
    end

    def full_path
      File.join(absolute_path, logo_filename)
    end
  
    def current_full_path
      File.join(RAILS_ROOT, 'public', self.logo)
    end

    def logo_url
      logo_path + logo_filename
    end
end
